/**
 * Created by ztt on 2017/11/17.
 */
var express = require('express');
var app = express();
var fs = require('fs');

/**
 * todo:跨域处理
 */
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('X-Powered-By', ' 3.2.1')
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});

//浏览器通过这种形式的url访问localhost/userlist?id=xxx&name=yyy，这种方式可以通过req.query.id获取参数的值
app.get('/organization/unique/', function (req, res, next) {
    let parentId = req.query.parentId;
    let name = req.query.name;
    console.log(`${parentId}=>${name}`);
    let result = {'result': Math.random() > 0.5, 'message': '编码已存在！'};
    console.log(`${parentId}=>${name}`, result);
    res.send(result);
});

//浏览器通过这种形式的url访问localhost/userlist?code=xxx，这种方式可以通过req.query.id获取参数的值
app.get('/role/unique/', function (req, res, next) {
    let code = req.query.code;
    let flag = Math.random() > 0.5;
    let result = {'result': flag, message: flag ? '编码已存在！' : '编码不存在！'};
    console.log(`${code}`, result);
    res.send(result);
});

app.get('/user/unique/:id', function (req, res) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('X-Powered-By', ' 3.2.1')
    res.header('Content-Type', 'application/json;charset=utf-8');
    fs.readFile(__dirname + '/' + 'users.json', 'utf-8', function (err, data) {
        data = JSON.parse(data);
        var user = data['user' + req.params.id];
        if (user) {
            res.send(true);
        } else {
            res.send(false)
        }
    })
});

var server = app.listen(3000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log('应用实例，访问地址为 http://%s:%s', host, port)
});
